package com.sky.task;

import com.alibaba.fastjson.JSON;
import com.hxc.pay.CommonPayTemplate;
import com.hxc.pay.wx.service.PaySuccessService;
import com.sky.mapper.user.OrderMapper;
import com.sky.pojo.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Component
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CommonPayTemplate commonPayTemplate;

    @Autowired
    private PaySuccessService paySuccessService;

   // @Scheduled(cron = "0 0/1 * * * *")
    public void cancelOrderTask(){
        System.out.println("-----定时任务扫描取消订单开始----");
//        1.获取支付超时的订单（15分钟未支付）
        Calendar before15Min = Calendar.getInstance();
        before15Min.add(Calendar.MINUTE,-15);
        List<Orders> ordersList = orderMapper.selectOrdersByStatusAndTime(Orders.PENDING_PAYMENT,before15Min.getTime(),null);

        if(ordersList!=null&&ordersList.size()>0){
            ordersList.forEach(orders -> {
//               2.调用微信的查单接口，确认支付状态是未支付
                String jsonStr = commonPayTemplate.queryOrder(orders.getNumber());
                String trade_state = JSON.parseObject(jsonStr, Map.class).get("trade_state").toString();
                if("NOTPAY".equals(trade_state)){
//                  3.调用微信的关单接口，关闭订单
                    commonPayTemplate.close(orders.getNumber());
//                  4.修改数据库订单的状态为取消支付
                    orderMapper.updateOrderStatusById(Orders.CANCELLED_ORDER,orders.getId());
                }

            });

        }

    }

    @Scheduled(cron = "0/5 * * * * *")
    public void queryOrderTask(){
//        1.查询当下未支付的订单
          System.out.println("----支付成功兜底方案定时任务---");
          Calendar before15Min = Calendar.getInstance();
          before15Min.add(Calendar.MINUTE,-15);
          List<Orders> ordersList = orderMapper.selectOrdersByStatusAndTime(Orders.PENDING_PAYMENT, null, before15Min.getTime());
          if (ordersList!=null&&ordersList.size()>0){
              ordersList.forEach(orders -> {
                  //        2.调用微信的查询接口，查询订单的支付状态
                  String jsonStr = commonPayTemplate.queryOrder(orders.getNumber());
                  String trade_state = JSON.parseObject(jsonStr, Map.class).get("trade_state").toString();
                  if("SUCCESS".equals(trade_state)){
                      // 3.如果是已支付，修改订单状态未已支付
                      //orderMapper.updateOrderStatusById(Orders.TO_BE_CONFIRMED,orders.getId());
                      paySuccessService.success(orders.getNumber());
                  }

              });
          }
    }
}
